#!/usr/bin/env python3
"""
Data Seeding Script
===================

Script to populate the database with sample data for development/testing.
"""

import os
import sys
from datetime import datetime
import logging

# Add project root to path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

from app import create_app, db
from app.models.user import User
from app.utils.database import DatabaseManager

def create_sample_users():
    """Create sample users for testing."""
    users_data = [
        {
            'username': 'admin',
            'email': 'admin@example.com',
            'password': 'AdminPass123!',
            'first_name': 'System',
            'last_name': 'Administrator',
            'is_active': True,
            'is_verified': True
        },
        {
            'username': 'johndoe',
            'email': 'john.doe@example.com',
            'password': 'JohnPass123!',
            'first_name': 'John',
            'last_name': 'Doe',
            'is_active': True,
            'is_verified': True
        },
        {
            'username': 'janedoe',
            'email': 'jane.doe@example.com',
            'password': 'JanePass123!',
            'first_name': 'Jane',
            'last_name': 'Doe',
            'is_active': True,
            'is_verified': False
        },
        {
            'username': 'testuser',
            'email': 'test@example.com',
            'password': 'TestPass123!',
            'first_name': 'Test',
            'last_name': 'User',
            'is_active': False,
            'is_verified': True
        }
    ]
    
    created_users = []
    db_manager = DatabaseManager(db)
    
    for user_data in users_data:
        try:
            # Check if user already exists
            existing_user = User.find_by_username(user_data['username'])
            if existing_user:
                logger.info(f"User '{user_data['username']}' already exists")
                continue
            
            # Create user
            user = User(
                username=user_data['username'],
                email=user_data['email'],
                first_name=user_data['first_name'],
                last_name=user_data['last_name'],
                is_active=user_data['is_active'],
                is_verified=user_data['is_verified']
            )
            user.set_password(user_data['password'])
            
            if db_manager.create(user):
                created_users.append(user)
                logger.info(f"Created user: {user.username}")
            else:
                logger.error(f"Failed to create user: {user_data['username']}")
        
        except Exception as e:
            logger.error(f"Error creating user {user_data['username']}: {str(e)}")
    
    return created_users

def main():
    """Main seeding function."""
    logger.info("Starting data seeding...")
    
    # Create Flask app
    app = create_app('development')
    
    with app.app_context():
        try:
            # Create sample users
            users = create_sample_users()
            
            logger.info(f"Data seeding completed. Created {len(users)} users.")
            
            # Print summary
            if users:
                logger.info("\nCreated users:")
                for user in users:
                    logger.info(f"  - {user.username} ({user.email})")
            
            return True
        
        except Exception as e:
            logger.error(f"Data seeding failed: {str(e)}")
            return False

if __name__ == '__main__':
    success = main()
    if success:
        logger.info("Data seeding completed successfully")
        sys.exit(0)
    else:
        logger.error("Data seeding failed")
        sys.exit(1)